package zcatt.examples.swt.graphics;


import java.io.IOException;
import java.io.InputStream;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Path;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class ImageAndFont {
	
	Image loadImage(String imagePath)
	{
		InputStream istream = ImageAndFont.class.getResourceAsStream(imagePath);
		if(istream == null)
			return null;
		//String filename = ImageAndFont.class.getResource("food.jpeg").toString();
		
		
		Image image = null;
		try {
			image = new Image(Display.getCurrent(), istream);			
		}
		finally {
			try {
				istream.close();			
			}
			catch(IOException ex) {}
		}		
		
		return image;
	}
	
	
	public Shell open(Display display)
	{
		Shell shell = new Shell(display);
		shell.setText("ImageAndFont SWT examples");
		
		
		Image image = loadImage("food.jpeg");
		Rectangle imgRect = image.getBounds();	
		
		FontData fd = shell.getFont().getFontData()[0];
		Font font = new Font(display, fd.getName(), 96, SWT.BOLD | SWT.ITALIC);
		
		shell.addPaintListener(new PaintListener() {
			@Override
            public void paintControl(PaintEvent e){
				GC gc = e.gc;
				Rectangle rect = shell.getClientArea();
				if(image != null)					
					gc.drawImage(image,  0, 0, imgRect.width, imgRect.height, 0, 0, rect.width, rect.height);
				
				Transform tr = new Transform(display);
				tr.translate(rect.width/4, rect.height/4);
				gc.setTransform(tr);
				
				gc.setAlpha(100);
				Path path = new Path(display);
				path.addString("FOOD", 0, 0, font);
				path.addString("美食", 0, 150, font);
				gc.setBackground(display.getSystemColor(SWT.COLOR_BLUE));
				gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
				gc.fillPath(path);
				gc.drawPath(path);

				path.dispose();
				tr.dispose();					
            }
		});
		shell.addDisposeListener(new DisposeListener() {

			@Override
			public void widgetDisposed(DisposeEvent e) {
				font.dispose();				
				if(image != null)
					image.dispose();
			}			
		});
		shell.setSize(shell.computeSize(imgRect.width, imgRect.height));
		shell.open();

		return shell;
	}

	public static void main(String[] args) {
		Display display = new Display();
		Shell shell = new ImageAndFont().open(display);
		
		while(!shell.isDisposed())
			if(!display.readAndDispatch())
				display.sleep();
		
		display.dispose();
	}

}
